import React, { useState, useImperativeHandle, useRef, useEffect } from 'react';
import ReactDom from 'react-dom';
import { useSize } from 'ahooks';
import { AntdBaseTable } from './TBaseTable';
import {
  applyTransforms,
  makeBuildTreeTransform,
  makeTreeModeTransform,
  //buildDrillTree,
} from 'ali-react-table';
import PropTypes from 'prop-types';

const BaseAntdBaseTable = React.forwardRef((props, ref) => {
  const tableRef = useRef();
  const {
    columns = [],
    dataSource = [],
    styles,
    trackWidth,
    getIndex,
    hoverIndex,
    ...rest
  } = props;
  const [openKeys, onChangeOpenKeys] = useState([]);
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [columnWidth, setColumnWidth] = useState(35);
  // const [colIndex, setColIndex] = useState(0);
  const dom = document.querySelector('body');
  useSize(dom);
  useImperativeHandle(
    ref,
    () => ({
      dom: (num = 0) => {
        // eslint-disable-next-line react/no-find-dom-node
        const table = ReactDom.findDOMNode(tableRef.current),
          tableBody = table.querySelector('.art-table-body');
        tableBody.scrollLeft = num; //传参数修改
      },
    }),
    [dataSource],
  );
  //表格排序
  // const compareFn = (a, b) => {
  //   if (a.stationName !== b.stationName) {
  //     return a.stationName.localeCompare(b.stationName);
  //   }
  // };

  if (!dataSource) return;
  // 注意 renderData 要用起来
  let tableDataSource = dataSource.map((item, index) => ({
    ...item,
    stationName: item?.stationName || '',
    index,
  }));
  const renderData = applyTransforms(
    {
      columns,
      dataSource: tableDataSource,
    },
    // 从平铺的数据中，根据 id/parent_id 字段构建出树状结构
    makeBuildTreeTransform('id', 'parent_id'),
    makeTreeModeTransform({
      primaryKey: 'id',
      openKeys,
      onChangeOpenKeys,
    }),
  );
  useEffect(() => {
    let columnWidth = (trackWidth - 150 - 64) / (renderData.columns.length - 2);
    setColumnWidth(columnWidth > 35 ? columnWidth : 35);
  }, [trackWidth, renderData.columns, rest.latitude]);
  return (
    <AntdBaseTable
      className={['compact', 'dark'].join(' ')}
      useVirtual={{ vertical: true, header: true }}
      // defaultColumnWidth={columnWidth}
      columns={renderData.columns}
      dataSource={renderData.dataSource}
      {...rest}
      ref={tableRef}
      style={{
        '--row-height': 28,
        '--bgcolor': '#4D535D',
        '--header-bgcolor': '#2A2F36',
        '--border-color': '#727272',
        ...styles,
      }}
    />
  );
});

BaseAntdBaseTable.propTypes = {
  columns: PropTypes.array,
  dataSource: PropTypes.array,
  ref: PropTypes.node,
  type: PropTypes.string,
  theme: PropTypes.bool,
  styles: PropTypes.any,
  getIndex: PropTypes.func,
  hoverIndex: PropTypes.number,
};

export default React.memo(BaseAntdBaseTable);
